package com.fance.controller;

import com.fance.async.EventModel;
import com.fance.async.EventProducer;
import com.fance.async.EventType;
import com.fance.model.EntityType;
import com.fance.model.HostHolder;
import com.fance.model.News;
import com.fance.service.LikeService;
import com.fance.service.NewsService;
import com.fance.util.ToutiaoUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author fance
 * @date 18-5-9 上午11:20
 */
@Controller
public class LikeController {

    @Autowired
    LikeService likeService;

    @Autowired
    HostHolder hostHolder;

    @Autowired
    NewsService newsService;

    @Autowired
    EventProducer eventProducer;


    @RequestMapping(path = "/like",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String like(@Param("newsId") int newsId){
        long likeCount = likeService.like(hostHolder.getUser().getId(), EntityType.ENTITY_NEWS,newsId);
        // 更新喜欢数
        News news = newsService.getById(newsId);
        newsService.updateLikeCount(newsId,(int)likeCount);

        EventModel eventModel = new EventModel(EventType.LIKE);
        eventModel.setEntityOwnerId(news.getUserId());
        eventModel.setActorId(hostHolder.getUser().getId());
        eventModel.setEntityId(newsId);
        eventModel.setEntityType(EntityType.ENTITY_NEWS);

        eventProducer.fireEvent(eventModel);
        return ToutiaoUtil.getJSONString(0,String.valueOf(likeCount));
    }

    @RequestMapping(path = {"/dislike"}, method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String disLike(@Param("newId") int newsId) {
        long likeCount = likeService.disLike(hostHolder.getUser().getId(),EntityType.ENTITY_NEWS, newsId);

        // 更新喜欢数
        newsService.updateLikeCount(newsId, (int) likeCount);
        return ToutiaoUtil.getJSONString(0,String.valueOf(likeCount));
    }
}
